package com.ypz.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ypz.reggie.dto.DishDto;
import com.ypz.reggie.entity.Dish;
import com.ypz.reggie.entity.DishFlavor;
import com.ypz.reggie.mapper.DishMapper;
import com.ypz.reggie.service.DishFlavorService;
import com.ypz.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 将dishDto中的数据分别保存到dish和dish_flavor中
     *
     * @param dishDto
     */
    @Override
    @Transactional//操作多张表，要加入这个注解，事务控制
    public void saveWithFlavor(DishDto dishDto) {
        //将dish存入数据库
        this.save(dishDto);
        //获取dish的ID,这个ID是数据库生成的，调用  this.save(dishDto);后就存到dishDto中了
        Long dishId = dishDto.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();

        //将dishId存入每一个dishFlavor中
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }
//这个stream的作用上面的for一样
//        flavors = flavors.stream().map((item) -> {
//            item.setDishId(dishId);
//            return item;
//        }).collect(Collectors.toList());

        //批量保存dishFlavor
        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 更具id查询菜品信息和口味
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {

        DishDto dishDto = new DishDto();

        //查询菜品信息
        Dish dish = this.getById(id);

        //准备查询口味的条件，不直接用id是因为查询的内容可能不止一个，而且这个id是Dish的id，不是口味的id
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,id);

        List<DishFlavor> flavorList = dishFlavorService.list(lqw);
        //将dish内容复制到dishDto
        BeanUtils.copyProperties(dish, dishDto);
        //设置dishDto口味
        dishDto.setFlavors(flavorList);

        return dishDto;
    }

    /**
     * 更新dish和dish_flavor
     * @param dishDto
     */
    @Override
    @Transactional//操作多张表，要加入这个注解，事务控制
    public void modifyWithFlavor(DishDto dishDto) {
        //更新dish
        this.updateById(dishDto);

        //删除相关flavor数据
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(lqw);

        //保存相关flavor数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        //将dishId存入每一个dishFlavor中
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);

    }


}
